#######################################
# Environnements
#######################################
if [ ! -n "${HOST+x}" ]; then export HOST=`/bin/uname -n`; fi
if [ ! -n "${AGENTFILE+x}" ]; then export AGENTFILE=$HOME/.$HOST.agent; fi
if [ ! -n "${HISTCONTROL+x}" ]; then export HISTCONTROL=ignoredups; fi
if [ ! -n "${SCRIPTHOME+x}" ]; then export SCRIPTHOME="/var/code/sap/scripts"; fi
if [ ! -n "${FUNCTIONS+x}" ]; then export FUNCTIONS="${SCRIPTHOME}/functions"; fi
if [ ! -n "${HOSTFILE+x}" ]; then export HOSTFILE="${SCRIPTHOME}/hosts_config"; fi
if [ ! -n "${LOGDIR+x}" ]; then export LOGDIR="/central/logs"; fi
if [ ! -n "${ORIGIN+x}" ]; then export ORIGIN=git://git; fi
if [ ! -n "${STATUSDIR+x}" ]; then export STATUSDIR="/central/logs/maint/status"; fi
#######################################
# FONCTIONS
#######################################
# Other servers
function list_hosts { $SCRIPTHOME/list_host.sh -s -q physical=y; }
function list_hosts_sb { $SCRIPTHOME/list_host.sh -s -q physical=y,env=sb; }
function list_hosts_tr { $SCRIPTHOME/list_host.sh -s -q physical=y,env=tr; }
function list_hosts_dev { $SCRIPTHOME/list_host.sh -s -q physical=y,env=dev; }
function list_hosts_qa { $SCRIPTHOME/list_host.sh -s -q physical=y,env=qa; }
function list_hosts_int { $SCRIPTHOME/list_host.sh -s -q physical=y,env=int; }
function list_hosts_prd { $SCRIPTHOME/list_host.sh -s -q physical=y,env=prd; }
function list_hosts_non_prd { $SCRIPTHOME/list_host.sh -s -q physical=y,env=\!prd; }
function list_hosts_util { $SCRIPTHOME/list_host.sh -s -q physical=y,env=util; }
function list_hosts_brbackup { $SCRIPTHOME/list_host.sh -s -q physical=y,brbackup=y; }
# AIX only
function list_hosts_aix { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y; }
function list_hosts_aix_sb { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=sb; }
function list_hosts_aix_tr { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=tr; }
function list_hosts_aix_dev { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=dev; }
function list_hosts_aix_qa { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=qa; }
function list_hosts_aix_int { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=int; }
function list_hosts_aix_prd { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=prd; }
function list_hosts_aix_non_prd { $SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=\!prd; }
# Linux only
function list_hosts_linux { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y; }
function list_hosts_linux_sb { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=sb; }
function list_hosts_linux_tr { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=tr; }
function list_hosts_linux_dev { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=dev; }
function list_hosts_linux_qa { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=qa; }
function list_hosts_linux_int { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=int; }
function list_hosts_linux_prd { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=prd; }
function list_hosts_linux_non_prd { $SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,env=\!prd; }
# Special case
function list_hosts_brbackup { $SCRIPTHOME/list_host.sh -s -q brbackup=y; }
function list_brbackup_by_host {  $SCRIPTHOME/list_host.sh -s -q server=$1,brbackup=y -c brbackup; }
function list_hosts_hacmp { $SCRIPTHOME/list_host.sh -s -q physical=y,hacmp=y; }
function list_hosts_sap { $SCRIPTHOME/list_host.sh -s -q physical=y,sap=y; }
function list_hosts_ora { $SCRIPTHOME/list_host.sh -s -q physical=y,ora=y; }
function list_hosts_brbackup_n { $SCRIPTHOME/list_host.sh -s -q brbackup=n; }
function list_hosts_maint { $SCRIPTHOME/list_host.sh -s -q maint=y; }
function list_hosts_all { $SCRIPTHOME/list_host.sh -s -q physical=y; }
function list_hosts_all_links { $SCRIPTHOME/list_host.sh -s -q server=all; }
function list_hosts_email_mon { $SCRIPTHOME/list_host.sh -s -q env=dev,server=\!sapnwd01; }
function list_sys_by_host { $SCRIPTHOME/list_host.sh -s -q server=$1 -c sid | tr '[a-z]' '[A-Z]'; }
function list_land_by_host { $SCRIPTHOME/list_host.sh -s -q server=$1 -c env; }
# Just up server
function list_hosts_aix_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_linux_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=linux,physical=y,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_sb_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=sb,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_tr_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=tr,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_dev_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=dev,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_qa_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=qa,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_int_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=int,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_prd_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=prd,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_aix_non_prd_up { checkhost `$SCRIPTHOME/list_host.sh -s -q os=aix,physical=y,env=\!prd,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_prd_up { checkhost `$SCRIPTHOME/list_host.sh -s -q physical=y,env=prd,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_all_up { checkhost `$SCRIPTHOME/list_host.sh -s -q physical=y,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_non_prd_up { checkhost `$SCRIPTHOME/list_host.sh -s -q physical=y,env=\!prd,maint=n` | /bin/grep -v Verifying|tr ' ' '\n'; }
function list_hosts_hacmp_up { checkhost `$SCRIPTHOME/list_host.sh -s -q physical=y,hacmp=y,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_email_mon_up { checkhost `$SCRIPTHOME/list_host.sh -s -q env=dev,server=\!sapnwd01`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_sap_up { checkhost `$SCRIPTHOME/list_host.sh -s -q physical=y,sap=y,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
function list_hosts_ora_up { checkhost `$SCRIPTHOME/list_host.sh -s -q physical=y,ora=y,maint=n`|/bin/grep -v 'Verifying host'|tr ' ' '\n'; }
#################################
#################################
# list of host to verify
# space seperated
# Accept [all]
#################################
function checkhost {
	unset TMPHOSTS
	HOSTS=( $(/bin/echo $@ | tr '[A-Z]' '[a-z]') )
	for a_HOSTS in ${HOSTS[@]}
	do
		if type list_hosts_$a_HOSTS &>/dev/null
		then
			TMPHOSTS="$TMPHOSTS $(list_hosts_$a_HOSTS)"
		else
			TMPHOSTS="$TMPHOSTS $a_HOSTS"
		fi
	done
	HOSTS=( $(echo $TMPHOSTS | tr ' ' '\n' | sort | uniq | tr '\n' ' ') )
	unset TMPHOSTS
	for s_HOSTNAME in ${HOSTS[@]}
	do
		printf '%s\c' "Verifying host $s_HOSTNAME..."
		PING=$(/usr/sbin/ping -q -c 1 -w 1 $s_HOSTNAME 2>&1 > /dev/null);
		if [ "$?" = "0" ]
		then
			/bin/echo "ok"
			TMPHOSTS="$TMPHOSTS $s_HOSTNAME"
		else
			/bin/echo "Host $s_HOSTNAME NOT pingable, skipping..."
		fi
	done
	TMPHOSTS=$(/bin/echo $TMPHOSTS | sed 's/^ //')
	printf '%s\n' "$TMPHOSTS" | sort | uniq
}
function create_jobid {
        echo `date +%Y%m%d%H%M%S`$RANDOM
}
###################################################
#######################################
# Check if an agent is running
# Start one if not
# Source config if yes
#######################################
function agent_check {
	if [[ $HOST = "saprmt01" ]] || [[ $HOST = "saprmt02" ]]
	then
		if agent_source | /bin/grep -q 'No agent file present'
		then
		   # if agent running but lost in the wild, creating another
			/bin/echo "Verifying agent processes..."
			LOGIN=$(id -u)
			if /bin/ps -u $LOGIN | /bin/grep -q ssh-agent
			then
				for AGENTPID in `/bin/ps -u $LOGIN | /bin/grep ssh-agent | /usr/bin/awk '{print $2}'`
				do
					/bin/echo "Killing pid $AGENTPID"
					kill $AGENTPID
				done
			fi
			/bin/echo "Starting agent"
			agent_start
		else
			/bin/echo "Listing agent"
			agent_list 2>&1 > /dev/null; RC=$?
		        if [[ $RC != 0 ]];then /bin/echo "Adding identity"; agent_add; fi
		fi
	fi
}
function agent_source {
	if [[ -f $AGENTFILE ]]
	then
		/bin/echo "Agent file present, sourcing it"
		. $AGENTFILE
		if ! grep -q SSH_AGENT_PID $AGENTFILE ; then \rm $AGENTFILE; echo "No agent file present ($AGENTFILE)"; fi
	else
		/bin/echo "No agent file present ($AGENTFILE)"
		/bin/echo "Execute agent_start"
	fi
}
function agent_add { /usr/bin/ssh-add; }
function agent_list { agent_source; /usr/bin/ssh-add -L; }
function agent_start { umask 077; ssh-agent -t 1h | /bin/grep -v "/bin/echo Agent pid" > $AGENTFILE && . $AGENTFILE; agent_add; }
function agent_kill { . $AGENTFILE; ssh-agent -k ; rm $AGENTFILE; }
function agent_restart { rm $AGENTFILE; agent_check; }
function agent_remove { agent_source;/usr/bin/ssh-add -D; }
#################################
# useful functions
#################################
function bk {
        cp -rp $1{,.`id -un`.`date +'%Y-%m-%d-%H-%M'`}
}
#################################
###################################################
# Dispatch 
###################################################
# Main dir
export DISPATCHDIR=/central/code/dispatch
# Where all scripts resides
export DISPATCHBIN=/var/code/dispatch
# All logs, worker and jobs
export DISLOGS=$DISPATCHDIR/logs
# worker data, like jobs sent
export DISWORKERDATA=$DISPATCHDIR/data
# worker log, like jobs start/end
export DISWORKERLOG=$DISLOGS/worker.log
# jobs data, with commands and options
export DISJOBSDATA=$DISPATCHDIR/jobs
# jobs definition, commands association, permissions, etc
export DISJOBSDEF=$DISPATCHDIR/etc/jobs_def
function dislogger {
	OPTIONS=$@
	TYPE=$1; shift
	HOSTNAME=$1; shift
	case $TYPE in 
		LOG) 
			
			FILE=$DISLOGS/${HOSTNAME}.log
			;;
		DATA)
			FILE=$DISWORKERDATA/${HOSTNAME}.data
			;;
		JOB)
			FILE=$DISJOBSDATA/${HOSTNAME}.job
			;;
	esac
	shift
	MESSAGE=$(echo $@)
}
function create_jobid {
	echo `date +%Y%m%d%H%M%S`$RANDOM
}
function create_job_data {
	#############################################################
	# pipe line to DISJOBS
	# jobid:from(user):from(host):to(host):command:options
	# ex.:
	# 2011122308221613472:b0528817:saprmt01:saprmt02:OSLEVEL:-s
	# $1 = JID
	# $2 = Target server
	# $3 = command like in list_jobs_def
	# $4 = options
	#############################################################
	if [ ! -z $1 ]; then TYPE=$1 ; else echo "ERROR: TYPE not entered" && return; fi
	[ `echo $TYPE | /bin/grep -Eqw 'COMMAND|LOG'` ] && echo "ERROR: TYPE doesn't seems to be good, needs to be COMMAND or LOG ($TYPE)" && return
	#############################################################
	shift
	if [ ! -z $1 ]; then JID=$1 ; else echo "ERROR: JID not entered" && return; fi
	[ -z "${JID##*[!0-9]*}" ] && echo "ERROR: JID doesn't seems to be good, needs to be only numbers" && return
	#############################################################
	shift
	if [ ! -z $1 ]; then TO=$1; else echo "ERROR: TARGET host not entered" && return; fi
	#############################################################
	shift
	if [ ! -z $1 ]; then COMMAND=$1; else echo "ERROR: COMMAND not entered" && return; fi
	s_COMMAND=$(list_jobs_def $COMMAND)
	[ `echo $s_COMMAND | /bin/grep -qw ERROR` ] && echo $s_COMMAND && return
	#############################################################
	shift
	[ ! -z "$1" ] && OPTIONS="$1"
	#############################################################
	ID=$(id -uln)
	FROM=$(uname -n)
	echo "$TYPE:$JID:$ID:$FROM:$TO:$COMMAND:$OPTIONS"
}
function list_jobs_def {
	# list jobs commands from file
	# commands must be unique
	# commands needs to be in sudoers
	# ex.:
	# OSLEVEL:/usr/bin/oslevel:root
	if [ -z $1 ]; then echo ERROR: Please specify a COMMAND tp look in $DISJOBSDEF; return; fi
	COMMAND=$1
	NUM=$(/usr/opt/freeware/bin/grep -c "^$COMMAND:" $DISJOBSDEF)
	case $NUM in 
	0)
		echo ERROR: No occurence of command $COMMAND found in DISJOBSDEF $DISJOBSDEF
		return
		;;
	1)
		/bin/grep -E "^${COMMAND}:" $DISJOBSDEF
		;;
	*)
		echo ERROR: More then one occurence of command $COMMAND
		return
		;;
	esac
}
